<template>
  <view>
    <!-- 单选组 -->
    <view v-if="selectionMode === 'radio'">
      <view
        v-for="(option, index) in radioOptions"
        :key="index"
        :class="['option-box', selectedRadioValue === option.value && 'option-box-active']"
        @click="onRadioSelect(option.value)"
      >
        {{ option.label }}
      </view>
    </view>

    <!-- 复选组 -->
    <view v-if="selectionMode === 'checkbox'">
      <view
        v-for="(option, index) in checkboxOptions"
        :key="index"
        :class="['option-box', isCheckboxSelected(option.value) && 'option-box-active']"
      >
        <checkbox
          :value="option.value"
          :checked="isCheckboxSelected(option.value)"
          @change="onCheckboxChange(option.value, $event)"
        />
        {{ option.label }}
      </view>
      <!-- 全选按钮 -->
      <view class="option-box" @click="selectAllCheckboxes">
        <checkbox :checked="areAllCheckboxesSelected" @change="onSelectAllChange">全选</checkbox>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectionMode: 'checkbox', // 'radio' 或 'checkbox'
      radioOptions: [
        { value: 'radio1', label: '单选1' },
        { value: 'radio2', label: '单选2' },
        { value: 'radio3', label: '单选3' },
      ],
      selectedRadioValue: '',
      checkboxOptions: [
        { value: 'checkbox1', label: '复选1' },
        { value: 'checkbox2', label: '复选2' },
        { value: 'checkbox3', label: '复选3' },
      ],
      selectedCheckboxValues: [],
    };
  },
  computed: {
    areAllCheckboxesSelected() {
      return this.selectedCheckboxValues.length === this.checkboxOptions.length;
    },
  },
  methods: {
    onRadioSelect(value) {
      this.selectedRadioValue = value;
    },
    isCheckboxSelected(value) {
      return this.selectedCheckboxValues.includes(value);
    },
    onCheckboxChange(value, event) {
      const isChecked = event.detail.value.length > 0;
      if (isChecked) {
        this.selectedCheckboxValues.push(value);
      } else {
        this.selectedCheckboxValues = this.selectedCheckboxValues.filter(v => v !== value);
      }
    },
    selectAllCheckboxes() {
      if (this.areAllCheckboxesSelected) {
        this.selectedCheckboxValues = [];
      } else {
        this.selectedCheckboxValues = this.checkboxOptions.map(option => option.value);
      }
    },
    onSelectAllChange(event) {
      this.selectAllCheckboxes();
    },
  },
};
</script>

<style scoped>
.option-box {
  padding: 10px;
  margin: 5px 0;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
}

.option-box-active {
  background-color: #f0f0f0;
}

checkbox {
  margin-right: 10px;
}
</style>
